﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Management;
using System.Drawing.Printing;
using System.Printing;

using System.ServiceProcess;

namespace common_park_spooler
{
    class PrintUtils
    {
        public static bool GetCheckSpoolerService()
        {
            bool bRet = false;

            ServiceController serviceController = new ServiceController("Spooler");
            try
            {
                if (serviceController.Status == ServiceControllerStatus.Stopped)
                { 
                    serviceController.Start();
                    bRet = true;
                }
            }
            catch (Exception ex)
            {
                string err = ex.ToString();
            }
            return bRet;
        }

        public static string GetDefaultPrinterName()
        {
            string printName = string.Empty;

            PrintDocument printDoc = new PrintDocument();
            for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
            {
                string pkInstalledPrinters = PrinterSettings.InstalledPrinters[i];
                if (printDoc.PrinterSettings.IsDefaultPrinter)
                {
                    printName = printDoc.PrinterSettings.PrinterName;
                    break;
                }
            }
            return printName;
        }

        public static void SetDefaultPrinterName(string printName)
        {
            ManagementObjectCollection objManagementColl;
            ManagementObjectSearcher objManagementSearch = new ManagementObjectSearcher("SELECT * FROM Win32_Printer");

            objManagementColl = objManagementSearch.Get();

            foreach (ManagementObject objManage in objManagementColl)
            {
                if (objManage["Name"].ToString() == printName)  // compares the name of printers
                {
                    objManage.InvokeMethod("SetDefaultPrinter", null); // invoke [SetDefaultPrinter] method 
                    break;
                }
            }
        }


        // 아래 항목부터는 무슨 내용인지 정확이 모르겠음;;
        // 테스트 진행을 해야 함;;
        public static bool PausePrintJob(string printerName, int printJobID)
        {
            bool isActionPerformed = false;
            string searchQuery = "SELECT * FROM Win32_PrintJob";
            ManagementObjectSearcher searchPrintJobs =
                     new ManagementObjectSearcher(searchQuery);
            ManagementObjectCollection prntJobCollection = searchPrintJobs.Get();
            foreach (ManagementObject prntJob in prntJobCollection)
            {
                System.String jobName = prntJob.Properties["Name"].Value.ToString();
                //Job name would be of the format [Printer name], [Job ID]
                char[] splitArr = new char[1];
                splitArr[0] = Convert.ToChar(",");
                string prnterName = jobName.Split(splitArr)[0];
                int prntJobID = Convert.ToInt32(jobName.Split(splitArr)[1]);
                string documentName = prntJob.Properties["Document"].Value.ToString();
                if (String.Compare(prnterName, printerName, true) == 0)
                {
                    if (prntJobID == printJobID)
                    {
                        prntJob.InvokeMethod("Pause", null);
                        isActionPerformed = true;
                        break;
                    }
                }
            }
            return isActionPerformed;
        }

        public static bool CancelPrintJob(string printerName, int printJobID)
        {
            bool isActionPerformed = false;
            string searchQuery = "SELECT * FROM Win32_PrintJob";
            ManagementObjectSearcher searchPrintJobs =
                   new ManagementObjectSearcher(searchQuery);
            ManagementObjectCollection prntJobCollection = searchPrintJobs.Get();
            foreach (ManagementObject prntJob in prntJobCollection)
            {
                System.String jobName = prntJob.Properties["Name"].Value.ToString();
                //Job name would be of the format [Printer name], [Job ID]
                char[] splitArr = new char[1];
                splitArr[0] = Convert.ToChar(",");
                string prnterName = jobName.Split(splitArr)[0];
                int prntJobID = Convert.ToInt32(jobName.Split(splitArr)[1]);
                string documentName = prntJob.Properties["Document"].Value.ToString();
                if (String.Compare(prnterName, printerName, true) == 0)
                {
                    if (prntJobID == printJobID)
                    {
                        //performs a action similar to the cancel 
                        //operation of windows print console
                        prntJob.Delete();
                        isActionPerformed = true;
                        break;
                    }
                }
            }
            return isActionPerformed;
        }


        //http://msdn.microsoft.com/en-us/library/system.printing.printsystemjobinfo.iscompleted(v=vs.110).aspx
        /*
        public static void SpotTroubleUsingJobAttributes(string printName)
        {
            PrintSystemJobInfo theJob = new PrintSystemJobInfo();
            
            if ((theJob.JobStatus & PrintJobStatus.Blocked) == PrintJobStatus.Blocked)
            {
                Console.WriteLine("The job is blocked.");
            }
            if (((theJob.JobStatus & PrintJobStatus.Completed) == PrintJobStatus.Completed)
                ||
                ((theJob.JobStatus & PrintJobStatus.Printed) == PrintJobStatus.Printed))
            {
                Console.WriteLine("The job has finished. Have user recheck all output bins and be sure the correct printer is being checked.");
            }
            if (((theJob.JobStatus & PrintJobStatus.Deleted) == PrintJobStatus.Deleted)
                ||
                ((theJob.JobStatus & PrintJobStatus.Deleting) == PrintJobStatus.Deleting))
            {
                Console.WriteLine("The user or someone with administration rights to the queue has deleted the job. It must be resubmitted.");
            }
            if ((theJob.JobStatus & PrintJobStatus.Error) == PrintJobStatus.Error)
            {
                Console.WriteLine("The job has errored.");
            }
            if ((theJob.JobStatus & PrintJobStatus.Offline) == PrintJobStatus.Offline)
            {
                Console.WriteLine("The printer is offline. Have user put it online with printer front panel.");
            }
            if ((theJob.JobStatus & PrintJobStatus.PaperOut) == PrintJobStatus.PaperOut)
            {
                Console.WriteLine("The printer is out of paper of the size required by the job. Have user add paper.");
            }

            if (((theJob.JobStatus & PrintJobStatus.Paused) == PrintJobStatus.Paused)
                ||
                ((theJob.HostingPrintQueue.QueueStatus & PrintQueueStatus.Paused) == PrintQueueStatus.Paused))
            {
                //HandlePausedJob(theJob);
                //HandlePausedJob is defined in the complete example.
            }

            if ((theJob.JobStatus & PrintJobStatus.Printing) == PrintJobStatus.Printing)
            {
                Console.WriteLine("The job is printing now.");
            }
            if ((theJob.JobStatus & PrintJobStatus.Spooling) == PrintJobStatus.Spooling)
            {
                Console.WriteLine("The job is spooling now.");
            }
            if ((theJob.JobStatus & PrintJobStatus.UserIntervention) == PrintJobStatus.UserIntervention)
            {
                Console.WriteLine("The printer needs human intervention.");
            }

        }
         */
    }
}
